<?php
/**
 *
 * @author yupoxiong<i@yupoxiong.com>
 */

declare (strict_types = 1);

namespace app\api\controller;

use app\api\exception\ApiServiceException;
use app\api\service\AuthService;
use app\common\validate\UserValidate;
use hg\apidoc\annotation as Apidoc;
use think\Request;
use think\response\Json;

/**
 * @Apidoc\Title("登录")
 * @Apidoc\Group("index")
 */
class AuthController {
	/**
	 * @Apidoc\Title("登录")
	 * @Apidoc\Desc("登录")
	 * @Apidoc\Method("POST")
	 * @Apidoc\Url("/api/auth/login")
	 * @Apidoc\Param("username",          type="string",require=true, desc="账号")
	 * @Apidoc\Param("password",          type="string",require=true, desc="密码")
	 * @Apidoc\Returned("data",        type="int",                 desc="desc")
	 */
	public function login(Request $request, UserValidate $validate, AuthService $service): Json {
		$param = $request->param();

		$check = $validate->scene('api_login')->check($param);
		if (!$check) {
			return api_error($validate->getError());
		}

		try {

			$username = $param['username'];
			$password = $param['password'];
			$result = $service->usernameLogin($username, $password);

			return api_success($result);
		} catch (ApiServiceException $e) {
			return api_error('登录失败，参考信息：' . $e->getMessage());
		}
	}
}